package com.specialtreasure.freightdepot.adapter;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.app.core.config.Constants;
import com.app.core.config.HttpApi;
import com.app.core.config.MyApp;
import com.app.core.util.CommonUtil;
import com.app.core.util.DateUtils;
import com.app.core.util.TimeUtils;
import com.app.core.util.UserUtils;
import com.specialtreasure.freightdepot.R;
import com.specialtreasure.freightdepot.model.BaseModel;
import com.specialtreasure.freightdepot.model.CLocation;
import com.specialtreasure.freightdepot.model.CLocationResp;
import com.specialtreasure.freightdepot.model.CUserResp;
import com.specialtreasure.freightdepot.model.MotorCadeBean;
import com.vondear.rxtools.RxKeyboardUtils;
import com.yanzhenjie.httpmodule.http.CallServer;
import com.yanzhenjie.httpmodule.http.Result;
import com.yanzhenjie.httpmodule.http.StringRequest;
import com.yanzhenjie.nohttp.Logger;
import com.yanzhenjie.nohttp.RequestMethod;
import com.yanzhenjie.nohttp.rest.CacheMode;
import com.yanzhenjie.nohttp.rest.Response;
import com.yanzhenjie.nohttp.rest.SimpleResponseListener;

import org.simple.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Administrator on 2017/8/10 0010.
 * 我的车队适配器
 */

public class MotorCadeAdapter extends BaseAdapter {
    List<MotorCadeBean> motorCadeDataList = new ArrayList<MotorCadeBean>();

    private Context context;
    private Integer cuserId;
    private String remark;

    public MotorCadeAdapter(Context context) {
        this.context = context;
    }

    @Override
    public int getCount() {
        if (motorCadeDataList != null && motorCadeDataList.size() > 0) {
            return motorCadeDataList.size();
        }

        return 0;
    }

    @Override
    public Object getItem(int i) {
        return motorCadeDataList.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        ViewHolder viewHolder = null;
        if (null == view) {
            view = View.inflate(viewGroup.getContext(), R.layout.item_moto_cade_list, null);
            viewHolder = new ViewHolder(view);
            view.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) view.getTag();
        }

        //适配数据
        final MotorCadeBean motorCadeBean = (MotorCadeBean) getItem(i);
        final ViewHolder viewHolder2 = viewHolder;

        if (motorCadeBean != null) {
            Integer group = motorCadeBean.getGroup();//0自有,1外协
            String distance = motorCadeBean.getDistance();//距离多少

            //判断分组
            if (group != null) {
                if (group == 0) {
                    viewHolder.tv_own.setText("自有");
                } else {
                    viewHolder.tv_own.setText("外协");
                }
            }

            viewHolder.tv_car_distance.setText("离我：" + distance + "公里");
            final CUserResp cUserResp = motorCadeBean.getcUserResp();

            if (cUserResp != null) {
                viewHolder.tv_name.setText(cUserResp.getCertName());
                viewHolder.tv_car_number.setText(cUserResp.getCarNumber());
                viewHolder.tv_remark.setText("备注：" + CommonUtil.checkString(cUserResp.getRemark()));

                if (cUserResp.getCarLength() != null && cUserResp.getCarType() != null) {
                    viewHolder.tv_car_height.setText(CommonUtil.checkString(cUserResp.getCarLength()) + "/" + CommonUtil.checkString(cUserResp.getCarType()));
                } else {
                    viewHolder.tv_car_height.setText(CommonUtil.checkString(cUserResp.getCarLength()) + CommonUtil.checkString(cUserResp.getCarType()));
                }

                if (cUserResp.getRunningRouteStart() != null && cUserResp.getRunningRoute() != null) {
                    viewHolder.tv_car_address.setText(CommonUtil.checkString(cUserResp.getRunningRouteStart()) + "/" + CommonUtil.checkString(cUserResp.getRunningRoute()));
                } else {
                    viewHolder.tv_car_address.setText(CommonUtil.checkString(cUserResp.getRunningRouteStart()) + CommonUtil.checkString(cUserResp.getRunningRoute()));
                }


                CLocationResp cLocation = cUserResp.getcLocation();
                if (cLocation != null) {
//                    viewHolder.tv_car_time.setText(DateUtils.convertTimeToFormat(cLocation.getLoginTime()) + " " + DateUtils.timeMinute(cLocation.getLoginTime()));
                    viewHolder.tv_car_time.setText(TimeUtils.formatTruck(cLocation.getLoginTime()));
                    viewHolder.tv_car_gps.setText(CommonUtil.checkString(cLocation.getLocateAddress()));
                }

                Integer carStatues = cUserResp.getCarStatues();//(0空车模式 1满载模式 2配货模式)
                if (carStatues != null) {
                    if (carStatues == 0) {
                        viewHolder.tv_car_status.setBackgroundDrawable(MyApp.getInstance().getResources().getDrawable(R.drawable.btn_fdb662_solid));
                        viewHolder.tv_car_status.setText("空车");
                        viewHolder.tv_content.setText("");
                    } else if (carStatues == 1) {
                        viewHolder.tv_car_status.setBackgroundDrawable(MyApp.getInstance().getResources().getDrawable(R.drawable.btn_bababa_solid));
                        viewHolder.tv_car_status.setText("运输中");
                        viewHolder.tv_content.setText("");
                    } else if (carStatues == 2) {
                        viewHolder.tv_car_status.setBackgroundDrawable(MyApp.getInstance().getResources().getDrawable(R.drawable.btn_fdb662_solid));
                        viewHolder.tv_car_status.setText("配货");
                        viewHolder.tv_content.setText(CommonUtil.checkString(cUserResp.getStartAddress() + "到" +
                                CommonUtil.checkString(cUserResp.getDestAddress()) + "需 , " + CommonUtil.checkString(cUserResp.getGoodsNum())));

                    } else {

                    }
                }

                //点击打电话
                viewHolder.iv_telphone.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent();
                        intent.setAction(Intent.ACTION_DIAL);
                        intent.setData(Uri.parse("tel:" + cUserResp.getPhone()));
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(intent);
                    }
                });


                //修改备注
                viewHolder2.iv_edit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        final EditText et = new EditText(context);
                        et.setFocusableInTouchMode(true);
                        et.requestFocus();
                        et.setFocusable(true);
                        new AlertDialog.Builder(context)
                                .setTitle("请输入备注内容")
                                .setView(et)
                                .setCancelable(false)
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        viewHolder2.tv_remark.setText("备注：" + et.getText().toString().trim());
                                        remark = et.getText().toString().trim();
                                        cuserId = cUserResp.getCuserId();
                                        updateRemark();
                                    }
                                })
                                .setNegativeButton("取消", null)
                                .create()
                                .show();

                        //自动弹出输入法
                        Timer timer = new Timer();
                        timer.schedule(new TimerTask() {
                            @Override
                            public void run() {
                                RxKeyboardUtils.showSoftInput(context, et);
                            }
                        }, 200);


                    }
                });

                viewHolder2.iv_delete.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        delete(motorCadeBean);
                    }
                });

            }

        }


        return view;
    }


    public static class ViewHolder {
        public View rootView;
        public TextView tv_name;
        public TextView tv_own;
        public TextView tv_car_number;
        public TextView tv_car_height;
        public TextView tv_car_address;
        public TextView tv_car_status;
        public TextView tv_car_time;
        public TextView tv_car_distance;
        public TextView tv_car_gps;
        public ImageView iv_telphone;
        public TextView tv_remark;
        //        public TextView tv_edit_remark;
        public TextView tv_content;
        public ImageView iv_delete;
        public ImageView iv_edit;

        public ViewHolder(View rootView) {
            this.rootView = rootView;
            this.tv_name = (TextView) rootView.findViewById(R.id.tv_name);
            this.tv_own = (TextView) rootView.findViewById(R.id.tv_own);
            this.tv_car_number = (TextView) rootView.findViewById(R.id.tv_car_number);
            this.tv_car_height = (TextView) rootView.findViewById(R.id.tv_car_height);
            this.tv_car_address = (TextView) rootView.findViewById(R.id.tv_car_address);
            this.tv_car_status = (TextView) rootView.findViewById(R.id.tv_car_status);
            this.tv_car_time = (TextView) rootView.findViewById(R.id.tv_car_time);
            this.tv_car_distance = (TextView) rootView.findViewById(R.id.tv_car_distance);
            this.tv_car_gps = (TextView) rootView.findViewById(R.id.tv_car_gps);
            this.tv_remark = (TextView) rootView.findViewById(R.id.tv_remark);
//            this.tv_edit_remark = (TextView) rootView.findViewById(R.id.tv_edit_remark);
            this.iv_telphone = (ImageView) rootView.findViewById(R.id.iv_telphone);
            this.tv_content = (TextView) rootView.findViewById(R.id.tv_content);
            this.iv_edit = (ImageView) rootView.findViewById(R.id.iv_edit);
            this.iv_delete = (ImageView) rootView.findViewById(R.id.iv_delete);
        }

    }

    public void setMotorCadeDataList(List<MotorCadeBean> motorCadeDataList) {
        this.motorCadeDataList = motorCadeDataList;
    }

    /**
     * 更新备注
     */
    private void updateRemark() {
        String url = Constants.HTTP_URL + HttpApi.UPDATECARSREMARK;
        StringRequest request = new StringRequest(url, RequestMethod.POST);
        request.add("token", UserUtils.getToken());
        request.add("cuserId", cuserId);
        request.add("remark", remark);

        request.setCacheMode(CacheMode.ONLY_REQUEST_NETWORK);

        CallServer.getInstance().request(Constants.ZERO, request, new SimpleResponseListener<Result<String>>() {
            @Override
            public void onSucceed(int what, Response<Result<String>> response) {
                super.onSucceed(what, response);
                String result = response.get().getResult();
                Logger.e("请求成功：" + result);
                BaseModel baseModel = JSON.parseObject(result, BaseModel.class);
                if (baseModel != null) {
                    Integer status = baseModel.getStatus();
                    String msg = baseModel.getMsg();
                    if (status != null && status == 0) {
                        Toast.makeText(context, "修改备注成功", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
                    }
                }


            }
        });
    }

    private void delete(MotorCadeBean motorCadeBean) {
        String url = Constants.HTTP_URL + HttpApi.deleteRelation;
        StringRequest request = new StringRequest(url, RequestMethod.POST);
        request.add("token", UserUtils.getToken());
        request.add("type", 0);//我的车队
        request.add("id", motorCadeBean.getcUserResp().getCuserId());

        request.setCacheMode(CacheMode.ONLY_REQUEST_NETWORK);

        CallServer.getInstance().request(Constants.ONE, request, new SimpleResponseListener<Result<String>>() {
            @Override
            public void onSucceed(int what, Response<Result<String>> response) {
                super.onSucceed(what, response);
                String result = response.get().getResult();
                Logger.e("请求成功：" + result);
                BaseModel baseModel = JSON.parseObject(result, BaseModel.class);
                if (baseModel != null) {
                    Integer status = baseModel.getStatus();
                    String msg = baseModel.getMsg();
                    if (status != null && status == 0) {
                        Toast.makeText(context, "删除成功", Toast.LENGTH_SHORT).show();
                        EventBus.getDefault().post(baseModel, Constants.UPDATEMETO);
                    } else {
                        Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
                    }
                }


            }
        });
    }

}
